from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from tictactoe.game.models import Game, Player
from django.utils import simplejson

def index(request):
    if request.method == 'POST':
        newgame = Game(name=request.POST['name'])
        newgame.save()
        request.session['lastgame']=newgame.key()
        player = Player(type=Player.PLAYER_HOST,name=request.POST['name'],session=request.session.session_key,game=newgame)
        player.save()
        return HttpResponseRedirect(newgame.get_absolute_url())
    games = Game.all().filter('state =',Game.STATE_WAITING_PLAYERS).order('-updated_on').fetch(3) #TODO
    returnobjs = dict(games = games)
    return render_to_response('index.html', returnobjs)

def ingame(request,game_key):
    game = Game.get(game_key)
    success = True
    if request.method == 'POST':
        ishost = yourmove = player = False
            
        try: 
            player = Player.all().filter("game =",game).filter("session =", request.session.session_key).fetch(1)[0]
            ishost = (player.type == Player.PLAYER_HOST)
        except IndexError: player = Player(type=Player.PLAYER_OBSERVER) # if not found, use an observer
        
        if ishost:
            host = player
        else:
            try: host = Player.all().filter("game =",game).filter("type =",Player.PLAYER_HOST).fetch(1)[0]
            except IndexError: host = Player(type=Player.PLAYER_OBSERVER) # this should not happen
        try: client = Player.all().filter("game =",game).filter("type =",Player.PLAYER_CLIENT).fetch(1)[0]
        except IndexError:
            if not ishost: # no client found, create a new client
                client = Player(type=Player.PLAYER_CLIENT,session=request.session.session_key,game=game)
                client.save()
            else: client = Player(type=Player.PLAYER_OBSERVER) # client already joined, change into observer mode
        
        if player.type in (Player.PLAYER_HOST,Player.PLAYER_CLIENT) and request.POST['action'] == 'move':
            turn = 2 ** int(request.POST['move'])
            state = game.get_state(host,client)
            if not ((host.state & turn) or (client.state & turn)) and ((ishost and state == Game.STATE_HOST_TURN) or (not ishost and state == Game.STATE_CLIENT_TURN)):
                if ishost:
                    host.state += turn
                    host.save()
                else:
                    client.state += turn
                    client.save()
            else:
                success = False

        returnobjs = {  'success': success, 'os': host.state, 'xs': client.state, 'x': client.get_moves(), 'o': host.get_moves(), 'state': game.get_state(host,client), 'isplayer': True,'ishost': ishost }
        return HttpResponse(simplejson.dumps(returnobjs), mimetype='application/javascript')
    return render_to_response('ingame.html',{'game':game})